<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 学生管理
 *
 * @icon fa fa-circle-o
 */
class Student extends Backend
{
    
    /**
     * Student模型对象
     * @var \app\admin\model\Student
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Student;
        $this->view->assign("sexList", $this->model->getSexList());
        $group = Db::name('auth_group_access')->where('uid', $this->auth->id)->find()['group_id'];
        $this->view->assign("group",$group);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            // 如果是老师,只查询老师名下的学生
            $wheres = [];
            $group = Db::name('auth_group_access')->where('uid', $this->auth->id)->find()['group_id'];
            if($group == 2){
                //查询当前老师下的所有学生
                $student_ids = Db::name('course')->alias('c')
                                        ->join('teacher t','c.teacher_id = t.id')
                                        ->join('order o','c.id = o.courseId')
                                        ->where(['t.admin_id' => $this->auth->id, 'o.status' => 'paid'])
                                        ->field('userId')
                                        ->select();
                $student_ids = array_unique(array_column($student_ids,'userId'));
                $wheres['id'] = ['in',$student_ids];
            }
            if($group == 4){
                $teacher_id = Db::name('helper')->where('admin_id',$this->auth->id)->find()['teacher_id'];
                $admin_id = Db::name('teacher')->where('id',$teacher_id)->find()['admin_id'];
                //查询当前老师下的所有学生
                $student_ids = Db::name('course')->alias('c')
                    ->join('teacher t','c.teacher_id = t.id')
                    ->join('order o','c.id = o.courseId')
                    ->where(['t.admin_id' => $admin_id, 'o.status' => 'paid'])
                    ->field('userId')
                    ->select();
//                dump($student_ids);exit;
                $student_ids = array_unique(array_column($student_ids,'userId'));
                $wheres['id'] = ['in',$student_ids];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)->where($wheres)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)->where($wheres)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            //计算学习课程和学习进度
            foreach ($list as &$v){
               //查询学生购买了哪些课程
                $course = Db::name('order')->alias('o')
                                ->join('course c','o.courseId = c.id')
                                ->where(['userId'=>$v['id'],'status' => 'paid'])
                                ->order('paid_time DESC')
                                ->field('c.*')
                                ->find();
                $v['course_name'] = $course['title'];
               // 查询出学习进度
                $count = Db::name('course_lesson_learn')->where(['user_id' => $v['id'], 'course_id' => $course['id']])->count();
                $v['plan'] = 0;
                if ($count !== 0) {
                    if($course['section_num'] !== 0){
                        $v['plan'] = round($count / $course['section_num'] * 100,2);
                    }
                }
                $v['plan'] .= '%';
                // 查询年级
                $grade_name = Db::name('grade')->where('id',$v['grade'])->find()['grade_name'];
                $v['grade'] = $grade_name;
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);

        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // 添加学生时将学生添加在User表中

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        // 如果是老师,只查询老师名下的课程
        $wheres = [];
        $group = Db::name('auth_group_access')->where('uid', $this->auth->id)->find()['group_id'];
        if($group == 2){
            //查询当前老师下的课程
            $course_id = Db::name('course')->alias('c')
                ->join('teacher t','c.teacher_id = t.id')
                ->where(['t.admin_id' => $this->auth->id])
                ->field('c.id')
                ->select();
            $course_id = array_unique(array_column($course_id,'id'));
            $wheres['c.id'] = ['in',$course_id];
        }
        //计算学习课程和学习进度
            //查询学生购买了哪些课程
            $course = Db::name('order')->alias('o')
                ->join('course c','o.courseId = c.id')
                ->where(array_merge(['userId'=>$ids,'status' => 'paid'],$wheres))
                ->order('paid_time DESC')
                ->field('c.id,c.title,c.section_num')
                ->select();
        foreach ($course as &$v){
            // 查询出学习进度
            $count = Db::name('course_lesson_learn')->where(['user_id' => $ids, 'course_id' => $v['id']])->count();
            $v['plan'] = 0;
            $v['count'] = $count;
            if ($count !== 0) {
                if($v['section_num'] !== 0){
                    $v['plan'] = round($count / $v['section_num'] * 100,'2');
                }
            }
            $v['plan'] .= '%';
        }
        $this->view->assign("row", $row);
        $this->view->assign("course", $course);
        return $this->view->fetch();
    }

}
